package com.nondo.rdp.auth.security.logic;

import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.event.PointApplicationEvent;
import com.nondo.rdp.auth.listener.PointApplicationListener;
import com.nondo.rdp.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

@Component
public class RegisterLogic {
    @Autowired
    UserService userService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 邀请用户注册，处理获得奖励
     *
     * @param user
     */
    public boolean inviteRegister(User user, Long inviterId) {
        //查找邀请的用户
        User inviterUser = this.userService.findOne(inviterId);
        if (inviterUser == null) {
            return false;
        }

        //注册用户获得vip
        user.setVip(1);
        user.setInviterId(inviterId);
        user.setExpireTime(getOneYearLater(new Date()));
        userService.save(user);

        //判断邀请的用户的总邀请次数
        int inviteCount = this.userService.countByInviterId(inviterId);

        if (inviteCount == 0) {//获得vip
            if (inviterUser.getVip() == 1 && inviterUser.getExpireTime().getTime() > new Date().getTime()) {//VIP未过期，则追加时间
                inviterUser.setExpireTime(getOneYearLater(inviterUser.getExpireTime()));
            } else {//vip已过期则直接加一年时间
                inviterUser.setVip(1);
                inviterUser.setExpireTime(getOneYearLater(new Date()));
            }
            userService.save(inviterUser);
        } else {//获得500积分
            //调用注册事件
            applicationEventPublisher.publishEvent(new PointApplicationEvent(this, user, PointApplicationListener.TYPE_INVITE_REGISTER));
        }

        return true;
    }

    /**
     * 获取一年后的时间
     *
     * @param date
     * @return
     */
    private Date getOneYearLater(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.YEAR, 1);//把日期往后增加一年.整数往后推,负数往前移动
        date = calendar.getTime();   //这个时间就是日期往后推一天的结果
        return date;
    }
}
